//
//  LoginViewController.swift
//  FlameB
//
//  Created by 连俊 on 2020/7/30.
//  Copyright © 2020 连俊. All rights reserved.
//

import UIKit
import SnapKit

class LoginViewController: BaseViewController {
    
    var phoneTextfield: UITextField!
    var ventifyTextfield: UITextField!
    
    var loginButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func buildView() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(viewDidEdit))
        view.addGestureRecognizer(tap)
        
        let view1 = UIView()
        view1.backgroundColor = UIColor.white
        view1.layer.borderColor = UIColor.black.cgColor
        view1.layer.borderWidth = 1/UIScreen.main.scale
        view1.layer.cornerRadius = 5
        view1.layer.masksToBounds = true
        view.addSubview(view1)
        view1.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(GTSize_width(200))
            make.left.equalTo(self.view.snp.left).offset(GTSize_width(20))
            make.right.equalTo(self.view).offset(-GTSize_width(20))
            make.height.equalTo(GTSize_width(17+28))
        }
        
        phoneTextfield = UITextField()
        let placeholderStr = "请输入手机号"
        let attributedString = NSMutableAttributedString(string: placeholderStr)
        attributedString.addAttributes([
            NSAttributedString.Key.font:UIFont.mainFont(ofSize: GTSize_width(17)),
            NSAttributedString.Key.foregroundColor:UIColor.init(rgb: 0xBBBCBB)
            ], range: NSRange(location: 0, length: placeholderStr.count))
        phoneTextfield.attributedPlaceholder = attributedString
        phoneTextfield.font = UIFont.mainFont(ofSize: GTSize_width(17))
        phoneTextfield.textColor = UIColor.black
//        phoneTextfield.keyboardType = .numberPad
        phoneTextfield.tag = 100
        phoneTextfield.clearButtonMode = .whileEditing
        phoneTextfield.addTarget(self, action: #selector(editChange(_ :)), for: .editingChanged)
        view1.addSubview(phoneTextfield)
        phoneTextfield.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(GTSize_width(4))
            make.bottom.equalToSuperview().offset(GTSize_width(-4))
            make.left.equalToSuperview().offset(GTSize_width(8))
            make.right.equalToSuperview().offset(GTSize_width(-4))
        }
        
        let view2 = UIView()
        view2.backgroundColor = UIColor.white
        view2.layer.borderColor = UIColor.black.cgColor
        view2.layer.borderWidth = 1/UIScreen.main.scale
        view2.layer.cornerRadius = 5
        view2.layer.masksToBounds = true
        view.addSubview(view2)
        view2.snp.makeConstraints { (make) in
            make.top.equalTo(view1.snp.bottom).offset(GTSize_width(40))
            make.left.equalTo(self.view.snp.left).offset(GTSize_width(20))
            make.right.equalTo(self.view).offset(-GTSize_width(20))
            make.height.equalTo(GTSize_width(17+28))
        }
        
        ventifyTextfield = UITextField()
        let ventifyPlaceholderStr = "请输入密码"
        let ventifyAttributedString = NSMutableAttributedString(string: ventifyPlaceholderStr)
        ventifyAttributedString.addAttributes([
            NSAttributedString.Key.font:UIFont.mainFont(ofSize: GTSize_width(17)),
            NSAttributedString.Key.foregroundColor:UIColor.init(rgb: 0xBBBCBB)
            ], range: NSRange(location: 0, length: ventifyPlaceholderStr.count))
        ventifyTextfield.attributedPlaceholder = ventifyAttributedString
        ventifyTextfield.font = UIFont.mainFont(ofSize: GTSize_width(17))
        ventifyTextfield.textColor = UIColor.black
//        ventifyTextfield.keyboardType = .numberPad
        ventifyTextfield.tag = 101
        ventifyTextfield.clearButtonMode = .whileEditing
        ventifyTextfield.addTarget(self, action: #selector(editChange(_ :)), for: .editingChanged)

        view2.addSubview(ventifyTextfield)
        ventifyTextfield.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(GTSize_width(4))
            make.bottom.equalToSuperview().offset(GTSize_width(-4))
            make.left.equalToSuperview().offset(GTSize_width(8))
            make.right.equalToSuperview().offset(GTSize_width(-4))
        }
        
        loginButton = UIButton()
        loginButton.layer.cornerRadius = 5
        loginButton.layer.masksToBounds = true
        loginButton.isEnabled = false
        loginButton.setTitle("登录", for: .normal)
        loginButton.setTitleColor(.white, for: .normal)
        loginButton.setBackgroundImage(UIImage.image(color: UIColor.init(rgb: 0xC29756)), for: .normal)
        loginButton.setTitleColor(.white, for: .disabled)
        loginButton.setBackgroundImage(UIImage.image(color: UIColor.init(rgb: 0xBFBFBF)), for: .disabled)
        loginButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: GTSize_width(17))
        loginButton.addTarget(self, action: #selector(loginButtonAction(_:)), for: .touchUpInside)
        view.addSubview(loginButton)
        loginButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view.snp.centerX)
            make.top.equalTo(view2.snp.bottom).offset(GTSize_width(150))
            make.size.equalTo(CGSize(width: GTSize_width(325), height: GTSize_width(45)))
        }
    }
    
    @objc private func viewDidEdit() {
        if phoneTextfield.isFirstResponder {
            phoneTextfield.resignFirstResponder()
        }
        if ventifyTextfield.isFirstResponder {
            ventifyTextfield.resignFirstResponder()
        }
    }
    
    func isPhoneNumber(phoneNumber:String) -> Bool {
        if phoneNumber.count == 0 {
            return false
        }
        let mobile = "^(1[3-9])\\d{9}$"
        let regexMobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        if regexMobile.evaluate(with: phoneNumber) == true {
            return true
        }else
        {
            return false
        }
    }
    
    @objc func loginButtonAction(_ sender: UIButton) {
        guard let phone = phoneTextfield.text, let pwd = ventifyTextfield.text else { return }
        guard isPhoneNumber(phoneNumber: phone) == true else {
            let alertView = UIAlertController(title: "提示", message: "手机号格式错误", preferredStyle: UIAlertController.Style.alert)
            let action1 = UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: { alert in
            })
            alertView.addAction(action1)
            self.present(alertView, animated: true, completion: nil)
            return
        }
        //存储用户信息
        DBService.shared.userLoginAction(phone, pwd: pwd, completion: { status in
            if status == .failure {
                let alertView = UIAlertController(title: "提示", message: "密码错误", preferredStyle: UIAlertController.Style.alert)
                let action1 = UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: { alert in
                })
                alertView.addAction(action1)
                self.present(alertView, animated: true, completion: nil)
            } else {
                let user = User(phone, pwd)
                user.saveToKC()
                
                ///打开数据库
                DBService.shared.openDB(with: phone)
                
                guard let delegate = UIApplication.shared.delegate as? AppDelegate else{
                   return
                }
                PageManager.shared.chooseRootViewController(delegate.window)
            }
        })
    }

    @objc func editChange(_ sender: UITextField) {
        if sender.tag == 100 {
            textFieldLimit(with: sender, limit: 11)
        }
        else if sender.tag == 101 {
            textFieldLimit(with: sender, limit: 6)
        }
        checkNextEnable()
    }
    
    fileprivate func textFieldLimit(with tf: UITextField, limit: Int)  {
        guard let text = tf.text else {return}
        guard text.count > limit else {return}
        tf.text = String(text.prefix(limit))
    }
    
    func checkNextEnable() {
        if (phoneTextfield.text?.count != 11 || ventifyTextfield.text?.count != 6) {
            loginButton.isEnabled = false
            return
        }
        loginButton.isEnabled = true
        view.endEditing(true)
    }
}
